let interstitialAd = null
let rewardedVideoAd = null
const maxWatchCount = 3 // 解析视频或图集时 每天需要用户观看的激励广告次数【提取按钮的激励广告】
const maxDownloadWatchCount = 3 // 下载视频时 每天用户需要观看激励广告次数 【保存视频】

module.exports = {
	// 导出maxWatchCount和maxDownloadWatchCount
	maxWatchCount,
	maxDownloadWatchCount,
	// 配置广告位
	adConfig: {
		interstitialAdUnitId: 'adunit-92a770e250b35ad9', // 插屏广告的单元ID
		rewardedVideoAdUnitId: 'adunit-1c9e7031ae98e53f', // 激励视频广告的单元ID
		customAdUnitId: 'adunit-93751c7a7c3c60f7', // 视频广告的单元ID
		requireRewardedVideo: false, // 提取按钮是否需要观看激励视频   开启：true  关闭：false
		requireDownloadVideo: false, // 下载按钮是否需要观看激励视频   开启：true  关闭：false
		enableInterstitialAd: false // 是否启用插屏广告   开启：true  关闭：false
	},
	//有流量主的可以自己选择是否开通  没有流量主的小伙伴 直接全部false就行  后续开通可以编辑后再提交小程序审核

	// 下载域名配置
	downloadConfig: {
		proxyDomain: '', // 中转下载域名，例如: "https://your-proxy-domain.com/download?url="
		enableProxy: false, // 是否启用中转下载   开启：true  关闭：false

		// 合法域名列表
		legalDomains: [
			'https://www.mynxn.cn;',
			'https://aip.baidubce.com;',
			'https://ali-ky.video.yximgs.com;',
			'https://api.ludeqi.com;',
			'https://aweme.snssdk.com;',
			'https://bd2.a.kwimgs.com;',
			'https://bdmov2.a.kwimgs.com;',
			'https://cdn.poizon.com;',
			'https://china-img.soulapp.cn;',
			'https://ci.xiaohongshu.com;',
			'https://cloud.video.taobao.com;',
			'https://cn-gddg-dx-bcache-16.bilivideo.com;',
			'https://cn-sccd-ct-01-27.bilivideo.com;',
			'https://down.jikebox.cn;',
			'https://f.us.sinaimg.cn;',
			'https://f.video.weibocdn.com;',
			'https://v9-default.365yg.com',
			'https://fb.video.weibocdn.com;',
			'https://fvdcdn.cp63.ott.cibntv.net;',
			'https://gd3.alicdn.com;',
			'https://get.wxshares.com;',
			'https://guangguang.cloudvideocdn.taobao.com;',
			'https://hw2.a.kwimgs.com;',
			'https://hwmov.a.kwimgs.com;',
			'https://image-cdn.poizon.com;',
			'https://img.alicdn.com;',
			'https://img2.soyoung.com;',
			'https://jsmov2.a.yximgs.com;',
			'https://jsmov3.a.yximgs.com;',
			'https://jvod.300hu.com;',
			'https://live-segment.cloudvideocdn.taobao.com;',
			'https://lz.sinaimg.cn;',
			'https://m.360buyimg.com;',
			'https://media.soyoung.com;',
			'https://mmbiz.qpic.cn;',
			'https://mp.weixin.qq.com;',
			'https://mpvideo.qpic.cn;',
			'https://o1.a.88cdn.com;',
			'https://oasis.video.weibocdn.com;',
			'https://p1-dy.byteimg.com;',
			'https://p1.a.yximgs.com;',
			'https://p1.douyinpic.com;',
			'https://p11.douyinpic.com;',
			'https://p2.a.yximgs.com;',
			'https://p26-sign.douyinpic.com;',
			'https://p26.douyinpic.com;',
			'https://p3-pc-sign.douyinpic.com;',
			'https://p3-ppx-sign.byteimg.com;',
			'https://p3-sign.douyinpic.com;',
			'https://p3-sign.toutiaoimg.com;',
			'https://p3.a.yximgs.com;',
			'https://p3.douyinpic.com;',
			'https://p4.a.yximgs.com;',
			'https://p5.a.yximgs.com;',
			'https://p5.douyinpic.com;',
			'https://p6-pc-sign.douyinpic.com;',
			'https://p6-ppx-sign.byteimg.com;',
			'https://p6-sign.douyinpic.com;',
			'https://p6.douyinpic.com;',
			'https://p9-pc-sign.douyinpic.com;',
			'https://p9-ppx.byteimg.com;',
			'https://p9-sign.douyinpic.com;',
			'https://p9.douyinpic.com;',
			'https://p95-sign.douyinpic.com;',
			'https://q.weishi.qq.com;',
			'https://shortv.cdp.qq.com;',
			'https://sns-img-hw.xhscdn.com;',
			'https://sns-img-qc.xhscdn.com;',
			'https://sns-video-al.xhscdn.com;',
			'https://sns-video-bd.xhscdn.com;',
			'https://sns-video-hw.xhscdn.com;',
			'https://sns-video-qc.xhscdn.com;',
			'https://sns-webpic-qc.xhscdn.com;',
			'https://svideo.qpic.cn;',
			'https://tb-video.bdstatic.com;',
			'https://tbm-auth.alicdn.com;',
			'https://tbvideo.ixiaochuan.cn;',
			'https://tx.stream.kg.qq.com;',
			'https://tx2.a.kwimgs.com;',
			'https://txmov2.a.kwimgs.com;',
			'https://txmov2.a.yximgs.com;',
			'https://upmov.a.kwimgs.com;',
			'https://us.sinaimg.cn;',
			'https://v.weishi.qq.com;',
			'https://v.xiaohongshu.com;',
			'https://v1-cold1.douyinvod.com;',
			'https://v1.douyinvod.com;',
			'https://v11-cold.douyinvod.com;',
			'https://v11-x.douyinvod.com;',
			'https://v11.douyinvod.com;',
			'https://v13-a.douyinvod.com;',
			'https://v13-a.toutiaovod.com;',
			'https://v18.toutiaovod.com;',
			'https://v2.kwaicdn.com;',
			'https://v26-cold.douyinvod.com;',
			'https://v26-default.365yg.com;',
			'https://v26-default.ixigua.com;',
			'https://v26-dy.ixigua.com;',
			'https://v26-web.douyinvod.com;',
			'https://v26-x.toutiaovod.com;',
			'https://v26.douyinvod.com;',
			'https://v26.huoshanvod.com;',
			'https://v26.toutiaovod.com;',
			'https://v27.douyinvod.com;',
			'https://v3-a.huoshanvod.com;',
			'https://v3-cdn-tos.ppxvod.com;',
			'https://v3-cold.douyinvod.com;',
			'https://v3-cold1.douyinvod.com;',
			'https://v3-cold3.douyinvod.com;',
			'https://v3-cold4.douyinvod.com;',
			'https://v3-default.365yg.com;',
			'https://v3-default.ixigua.com;',
			'https://v3-dy.ixigua.com;',
			'https://v3-jianying.vlabvod.com;',
			'https://v3-web.douyinvod.com;',
			'https://v3-webc.douyinvod.com;',
			'https://v3-x.douyinvod.com;',
			'https://v3-x.toutiaovod.com;',
			'https://v3-xg-web-pc.ixigua.com;',
			'https://v3-y.douyinvod.com;',
			'https://v3-z.douyinvod.com;',
			'https://v3.douyinvod.com;',
			'https://v3.huoshanvod.com;',
			'https://v3.toutiaovod.com;',
			'https://v5-cold.douyinvod.com;',
			'https://v5-colda.douyinvod.com;',
			'https://v5-coldb.douyinvod.com;',
			'https://v5-coldc.douyinvod.com;',
			'https://v5-colde.douyinvod.com;',
			'https://v5-coldy.douyinvod.com;',
			'https://v5-f.douyinvod.com;',
			'https://v5-g.douyinvod.com;',
			'https://v5-h.douyinvod.com;',
			'https://v5-i.douyinvod.com;',
			'https://v5-j.douyinvod.com;',
			'https://v5-x.toutiaovod.com;',
			'https://v5.douyinvod.com;',
			'https://v6-cdn-tos.ppxvod.com;',
			'https://v6-cold.douyinvod.com;',
			'https://v6-cold1.douyinvod.com;',
			'https://v6-cold2.douyinvod.com;',
			'https://v6-default.365yg.com;',
			'https://v6-default.ixigua.com;',
			'https://v6-dy.ixigua.com;',
			'https://v6-jianying.vlabvod.com;',
			'https://v6-x.douyinvod.com;',
			'https://v6.douyinvod.com;',
			'https://v6.huoshanvod.com;',
			'https://v6.toutiaovod.com;',
			'https://v83-016.douyinvod.com;',
			'https://v83-017.douyinvod.com;',
			'https://v86-b.douyinvod.com;',
			'https://v9-cold.douyinvod.com;',
			'https://v9-cold1.douyinvod.com;',
			'https://v9-cold2.douyinvod.com;',
			'https://v9-default.ixigua.com;',
			'https://v9-dy.ixigua.com;',
			'https://v9-x.toutiaovod.com;',
			'https://v9-xg-web-pc.ixigua.com;',
			'https://v9.douyinvod.com;',
			'https://v9.huoshanvod.com;',
			'https://v95-hb.douyinvod.com;',
			'https://v95-hn-cold.douyinvod.com;',
			'https://v95-p-cold.douyinvod.com;',
			'https://v95-p.douyinvod.com;',
			'https://v95-sh-cold.douyinvod.com;',
			'https://v95-sz-cold.douyinvod.com;',
			'https://v95-zj-cold.douyinvod.com;',
			'https://v95-zj.douyinvod.com;',
			'https://v95.douyinvod.com;',
			'https://v95.toutiaovod.com;',
			'https://v99-coldx.douyinvod.com;',
			'https://vd2.bdstatic.com;',
			'https://vd3.bdstatic.com;',
			'https://vd4.bdstatic.com;',
			'https://video.izuiyou.com;',
			'https://video.momocdn.com;',
			'https://vodkgeyttp8.vod.126.net;',
			'https://water.quanminyouxi.cn;',
			'https://ww3.sinaimg.cn;',
			'https://wx1.sinaimg.cn;',
			'https://wx2.sinaimg.cn;',
			'https://wx3.sinaimg.cn;',
			'https://wx4.sinaimg.cn;',
			'https://xximg1.meitudata.com;',
			'https://zzx.sinaimg.cn;'
		]
	},

	// 自定义广告事件处理
	handleCustomAd: {
		onLoad: function () {
			console.log('自定义广告加载成功')
		},
		onError: function (err) {
			console.error('自定义广告加载失败', err)
		},
		onClose: function () {
			console.log('自定义广告关闭')
		}
	},

	// 初始化广告计数器
	initAdCounters: function () {
		const isFirstTime = !wx.getStorageSync('hasInitialized')
		if (isFirstTime) {
			const currentDate = new Date().toDateString()
			wx.setStorageSync('watchCount', 0)
			wx.setStorageSync('downloadWatchCount', 0)
			wx.setStorageSync('watchDate', currentDate)
			wx.setStorageSync('downloadWatchDate', currentDate)
			wx.setStorageSync('hasInitialized', true)
		}
	},

	// 创建插屏广告
	createInterstitialAd: function () {
		if (!this.adConfig.enableInterstitialAd) {
			console.log('插屏广告已关闭')
			return false
		}

		if (wx.createInterstitialAd) {
			interstitialAd = wx.createInterstitialAd({ adUnitId: this.adConfig.interstitialAdUnitId })
			interstitialAd.onLoad(() => {
				console.log('插屏广告加载成功')
			})
			interstitialAd.onError(err => {
				console.error('插屏广告加载失败', err)
			})
			interstitialAd.onClose(() => {
				console.log('插屏广告关闭')
			})
			return true
		}
		return false
	},

	// 显示插屏广告
	showInterstitialAd: function (delay = 0) {
		if (!this.adConfig.enableInterstitialAd) {
			console.log('插屏广告已关闭，不显示')
			return
		}

		if (interstitialAd) {
			if (delay > 0) {
				setTimeout(() => {
					this._showAd()
				}, delay)
			} else {
				this._showAd()
			}
		}
	},

	// 内部方法：实际显示插屏广告
	_showAd: function () {
		interstitialAd.show().catch(err => {
			console.error('插屏广告显示失败', err)
			// 重新加载并尝试显示
			interstitialAd
				.load()
				.then(() => {
					return interstitialAd.show()
				})
				.catch(err => {
					console.error('插屏广告重试显示失败', err)
				})
		})
	},

	// 创建激励视频广告
	createRewardedVideoAd: function () {
		if (wx.createRewardedVideoAd) {
			rewardedVideoAd = wx.createRewardedVideoAd({ adUnitId: this.adConfig.rewardedVideoAdUnitId })
			rewardedVideoAd.onError(err => {
				console.error('激励视频广告加载失败', err)
			})
		}
	},

	// 显示激励视频广告
	showRewardedVideoAd: function (callback) {
		if (rewardedVideoAd) {
			const currentDate = new Date().toDateString() // 获取当前日期
			const storedDate = wx.getStorageSync('watchDate') // 获取存储的日期
			let currentWatchCount = wx.getStorageSync('watchCount') || 0 // 获取当前观看次数

			// 只在日期变化时重置计数
			if (storedDate && storedDate !== currentDate) {
				console.log('解析功能：新的一天，重置激励广告观看次数')
				wx.setStorageSync('watchCount', 0)
				wx.setStorageSync('watchDate', currentDate)
				currentWatchCount = 0 // 重置后，当前次数为0
			}

			if (currentWatchCount < maxWatchCount) {
				// 先显示提示框
				wx.showModal({
					title: '观看激励广告',
					content: '观看广告后将获得提取视频的权限，是否观看？',
					confirmText: '观看',
					cancelText: '不观看',
					success: res => {
						if (res.confirm) {
							// 用户点击确定，显示广告
							// 先注册关闭事件监听器
							rewardedVideoAd.onClose(res => {
								// Ensure the listener is removed after firing once to prevent multiple calls
								rewardedVideoAd.offClose()

								if (res && res.isEnded) {
									console.log('用户观看了完整视频 (for parsing)')
									const newWatchCount = (wx.getStorageSync('watchCount') || 0) + 1 // 增加观看次数
									wx.setStorageSync('watchCount', newWatchCount) // 存储新的观看次数
									wx.setStorageSync('watchDate', currentDate) // Ensure date is updated on successful watch
									callback() // 调用传入的回调函数
								} else {
									console.log('用户未观看完整视频 (for parsing)')
									wx.showToast({
										title: '需要观看完整视频',
										icon: 'none'
									})
								}
							})

							// 然后再显示广告
							rewardedVideoAd.show().catch(err => {
								console.error('激励视频显示失败', err)
								// Attempt to load and show again
								rewardedVideoAd
									.load()
									.then(() => rewardedVideoAd.show())
									.catch(loadErr => {
										console.error('激励视频重试加载/显示失败', loadErr)
										wx.showToast({ title: '广告加载失败', icon: 'none' })
									})
							})
						} else {
							// 用户点击取消
							wx.showToast({
								title: '未观看广告，无法提取视频',
								icon: 'none'
							})
						}
					}
				})
			} else {
				// 如果观看次数达到上限，直接调用回调
				console.log('今日解析广告观看次数已达上限，直接执行操作')
				callback()
			}
		} else {
			console.warn('激励视频广告对象尚未初始化或加载失败。')
			// Optionally, show a toast message
			// wx.showToast({ title: '广告服务异常', icon: 'none' });
			callback()
		}
	},

	// 检查是否需要观看激励视频
	checkRewardedVideoRequirement: function () {
		return this.adConfig.requireRewardedVideo
	},

	// 检查并更新日期计数
	checkAndUpdateDateCount: function () {
		const currentDate = new Date().toDateString()
		const storedDate = wx.getStorageSync('downloadWatchDate')

		// 如果是新的一天，重置计数
		if (storedDate !== currentDate) {
			console.log('新的一天，重置广告观看次数')
			wx.setStorageSync('watchCount', 0)
			wx.setStorageSync('downloadWatchCount', 0)
			wx.setStorageSync('watchDate', currentDate)
			wx.setStorageSync('downloadWatchDate', currentDate)
			return true
		}
		return false
	},

	// 处理下载和保存操作的激励广告逻辑
	handleDownloadWithAd: function (callback) {
		// 首先判断是否开启下载广告
		if (this.adConfig.requireDownloadVideo) {
			// 检查是否是新的一天
			this.checkAndUpdateDateCount()

			const currentDownloadWatchCount = wx.getStorageSync('downloadWatchCount') || 0
			console.log('当前下载广告观看次数：', currentDownloadWatchCount)

			if (currentDownloadWatchCount < maxDownloadWatchCount) {
				// 先显示提示框
				wx.showModal({
					title: '观看激励广告',
					content: '观看广告后将获得下载视频的权限，是否观看？',
					confirmText: '观看',
					cancelText: '不观看',
					success: res => {
						if (res.confirm) {
							// 用户点击确定，显示广告
							this.createRewardedVideoAd()
							// 先注册关闭事件监听器
							rewardedVideoAd.onClose(res => {
								if (res && res.isEnded) {
									console.log('用户观看了完整视频 (for download)')
									const newDownloadWatchCount = currentDownloadWatchCount + 1
									wx.setStorageSync('downloadWatchCount', newDownloadWatchCount)
									callback() // 只在用户完整观看视频后执行回调
								} else {
									console.log('用户未观看完整视频 (for download)')
									wx.showToast({
										title: '需要观看完整视频',
										icon: 'none'
									})
								}
							})

							// 然后再显示广告
							rewardedVideoAd.show().catch(err => {
								console.error('激励视频显示失败', err)
								rewardedVideoAd
									.load()
									.then(() => rewardedVideoAd.show())
									.catch(loadErr => {
										console.error('激励视频重试加载/显示失败', loadErr)
										wx.showToast({ title: '广告加载失败', icon: 'none' })
									})
							})
						} else {
							// 用户点击取消
							wx.showToast({
								title: '未观看广告，无法下载',
								icon: 'none'
							})
						}
					}
				})
			} else {
				// 已达到最大观看次数，直接执行回调
				console.log('今日下载广告观看次数已达上限，直接执行操作')
				callback()
			}
		} else {
			// 未开启下载广告，直接执行回调
			console.log('下载广告未开启，直接执行操作')
			callback()
		}
	},

	// 检查URL是否在合法域名列表中
	checkLegalDomain: function (url) {
		if (!url) return false

		// 提取域名部分
		let domainRegex = /^(https?:\/\/[^\/\n?]+)/i
		let matches = url.match(domainRegex)

		if (!matches || !matches[1]) return false

		const urlDomain = matches[1] + ';'
		console.log('检查域名:', urlDomain)

		// 只进行严格匹配，不再进行主域名匹配
		const isLegal = this.downloadConfig.legalDomains.includes(urlDomain)

		if (isLegal) {
			console.log('域名在合法列表中 - 匹配成功')
		} else {
			console.log('域名不在合法列表中')
		}

		return isLegal
	},

	// 获取中转下载URL
	getProxyUrl: function (originalUrl) {
		console.log('获取中转URL, 当前enableProxy设置:', this.downloadConfig.enableProxy)

		if (!originalUrl) {
			console.log('获取中转URL失败: 原始URL为空')
			return ''
		}

		if (!this.downloadConfig.enableProxy) {
			console.log('获取中转URL失败: 中转下载功能已禁用')
			return ''
		}

		// 从本地存储获取最新的中转域名
		const storedProxyDomain = wx.getStorageSync('proxyDomain')
		const proxyDomain = storedProxyDomain || this.downloadConfig.proxyDomain
		console.log('中转域名:', proxyDomain)

		if (!proxyDomain) {
			console.log('获取中转URL失败: 未配置中转域名')
			return ''
		}

		// 使用中转域名拼接原始URL
		const finalUrl = proxyDomain + encodeURIComponent(originalUrl)
		console.log('最终中转URL:', finalUrl)
		return finalUrl
	},

	// 初始化下载配置
	initDownloadConfig: function () {
		console.log('初始化下载配置...')
		console.log('默认配置:', {
			proxyDomain: this.downloadConfig.proxyDomain,
			enableProxy: this.downloadConfig.enableProxy
		})

		// 从本地存储加载中转域名
		const storedProxyDomain = wx.getStorageSync('proxyDomain')
		if (storedProxyDomain) {
			console.log('从本地存储加载中转域名:', storedProxyDomain)
			this.downloadConfig.proxyDomain = storedProxyDomain
		}

		// 从本地存储加载是否启用中转下载
		const enableProxyStorage = this.downloadConfig.enableProxy
		console.log(
			'本地存储中的enableProxy值:',
			enableProxyStorage,
			'类型:',
			typeof enableProxyStorage
		)

		// 只有当明确设置为false时才禁用
		if (enableProxyStorage == false) {
			console.log('从本地存储加载中转下载设置: 禁用')
			this.downloadConfig.enableProxy = false
			wx.setStorage({
				key: 'enableProxy',
				data: false
			})
		} else {
			// 确保启用
			console.log('确保中转下载功能启用')
			this.downloadConfig.enableProxy = true
			// 更新本地存储
			wx.setStorage({
				key: 'enableProxy',
				data: true
			})
		}

		console.log('最终配置:', {
			proxyDomain: this.downloadConfig.proxyDomain,
			enableProxy: this.downloadConfig.enableProxy
		})
	},

	// 保存中转域名设置
	saveProxyDomain: function (proxyDomain) {
		// 保存到配置
		this.downloadConfig.proxyDomain = proxyDomain

		// 保存到本地存储
		wx.setStorage({
			key: 'proxyDomain',
			data: proxyDomain
		})
	}
}
